package com.spring.mvc.session.client;

import java.io.IOException;
import java.net.URL;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.spring.mvc.util.MathUtil;
import com.spring.mvc.util.StringUtil;

public class SessionFilter implements Filter {

	public static final String SESSION_COOKIE_NAME="JSESSIONID-CLUSTER";
	private SessionService service;
	
	public void destroy() {
		
	}

	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)arg0;
		HttpServletResponse response=(HttpServletResponse)arg1;
		
		//通过客户端Cookie获取sessionId
		String sessionId=null;
		Cookie[] cc=request.getCookies();
		if(null != cc){
			for(Cookie cookie:cc){
				if(SESSION_COOKIE_NAME.equalsIgnoreCase(cookie.getName())){
					sessionId=cookie.getValue();
					break;
				}
			}
		}
		//如果sessionId为空，生成sessionId,放入cookie
		if(StringUtil.isEmpty(sessionId)){
			sessionId=generateSessionId();
			Cookie cookie=new Cookie(SESSION_COOKIE_NAME, sessionId);
			String domain=this.service.getDomainName();
			
			URL aUrl=new URL(new String(request.getRequestURL()));
			if(aUrl.getHost()==null){
				domain=aUrl.getHost();
			}else{
				domain="";
			}
			if(StringUtil.isNotEmpty(domain)){
				cookie.setDomain(domain);
			}
			//会话Cookie
			cookie.setMaxAge(-1);//随浏览器的关闭自动消失
			String contextPath=request.getContextPath();
			if(StringUtil.isNotEmpty(contextPath)){
				cookie.setPath(contextPath);
			}else{
				cookie.setPath("/");
			}
			
			if(request.isSecure()){//判断请求是否用一个安全通道
				cookie.setSecure(true);
			}
			response.addCookie(cookie);
		}
		ServletRequestWapper req= new ServletRequestWapper(sessionId,request);
		req.setSessionService(this.service);
		
		arg2.doFilter(req, response);
	}

	private String generateSessionId() {
		String s=UUID.randomUUID().toString().toUpperCase();
		return s.replaceAll("-", "");
	}

	public void init(FilterConfig config) throws ServletException {
		String confDir=config.getInitParameter("conf.dir");
		if(StringUtil.isEmpty(confDir)){
			confDir=config.getServletContext().getRealPath("/WEB-INF/config");
		}
		this.service=new SessionServiceImpl();
		
		String domainName=config.getInitParameter("domain.name");
		if(null == domainName){
			domainName="";
		}
		
		this.service.setDomainName(domainName);
		
		int hashIdx=MathUtil.toInt(config.getInitParameter("hash.index"),1);
		if(hashIdx<=0 || hashIdx>=10){
			hashIdx=1;
		}
		this.service.setHashIndex(hashIdx);
	}

}
